﻿/*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */


#region using 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Windows.Forms;
using System.IO;
using NetBay.Core.BusinessEntities;
using System.Net.Mail;
#endregion

namespace Rio.Windows.Services.BusinessLayer
{
    public class BusinessLayer
    {
        /// <summary>
        /// Init Database
        /// </summary>
        /// <param name="p_sDirectory">Directory of the configuration file</param>
        /// <param name="p_sFileName">Name of the configuratin file</param>
        /// <param name="p_sDataBaseConnection">Name of the database connection</param>
        public static void InitDatabase(string p_sDirectory, string p_sFileName, string p_sDataBaseConnection)
        {
            DataAccessLayer.DataAccessManager.Init(p_sDirectory, p_sFileName, p_sDataBaseConnection);
        }

        /// <summary>
        /// Is the database online
        /// </summary>
        /// <returns>True if the database is online</returns>
        public static bool IsDataBaseOnline()
        {
            return DataAccessLayer.DataAccessManager.IsDataBaseActive();
        }

        /// <summary>
        /// Send all alerts of the day
        /// </summary>
        public static void SendAlerts(string p_sSmtpServer, string p_sSmtpLogin, string p_sSmtpPassword)
        { 
            // Get all alerts of the day
            List<Alert> l_lstAlertes = TranslatorLayer.AlertTranslator.TranslateAlert(DataAccessLayer.DataAccessManager.GetAlertOfTheDay());

            Dictionary<Alert, List<Group>> l_oDicAlertGoups = new Dictionary<Alert, List<Group>>();

            // Foreach alert get all groups associated
            foreach (Alert l_oAlert in l_lstAlertes)
            {
                l_oDicAlertGoups.Add(l_oAlert, TranslatorLayer.GeneralGroupTranslator.TranslateGroup(DataAccessLayer.DataAccessManager.GetGroupsOfAnAlert(l_oAlert.Identifier)));
            }

            // Foreach group get all users
            Dictionary<Alert, List<User>> l_oDicAlertUsers = new Dictionary<Alert, List<User>>();
            foreach (Alert l_oCurrentAlert in l_oDicAlertGoups.Keys)
            {
                
                List<User> l_oUser = new List<User>();
                // First getting all users from each group
                foreach (Group l_oCurrentGroup in l_oDicAlertGoups[l_oCurrentAlert])
                {
                    List<User> l_oTempUsers = TranslatorLayer.UserTranslator.TranslateUsers(DataAccessLayer.DataAccessManager.GetUsersFromAGroup(l_oCurrentGroup.Identifier));
                    //Adding the user to the list of all users for the current alert
                    foreach (User l_oTempUser in l_oTempUsers )
                    {
                        //If the user has not already been added from another group we add it for this alert
                        if (!l_oUser.Contains(l_oTempUser))
                            l_oUser.Add(l_oTempUser);
                    }
                }
                l_oDicAlertUsers.Add(l_oCurrentAlert, l_oUser);
            }

            // Foreach item in dictionnary send email alert
            foreach (Alert l_oCurrentAlert in l_oDicAlertUsers.Keys)
            {
                //Execute the action
                if( l_oCurrentAlert.ActionId.HasValue && l_oCurrentAlert.ActionId > 0)
                {
                    DataAccessLayer.DataAccessManager.ExecuteAlertAction(l_oCurrentAlert.Identifier);
                }

                //Send email
                List<MailAddress> l_oLstMailAddresses = new List<MailAddress>();
                foreach (User l_oCurrentUser in l_oDicAlertUsers[l_oCurrentAlert])
                {
                    try
                    {
                        l_oLstMailAddresses.Add(new MailAddress(l_oCurrentUser.Email));
                    }
                    catch
                    {
                        NetBay.Core.Log.LogManager.Instance().LogError("-------- Exception in SendAlerts EmailAdress is not valid [" + l_oCurrentUser.Email + "]"); 
                    }
                }

                try
                {
                    MailAddress l_oSenderMailAdress = new MailAddress(l_oCurrentAlert.UserEmail);
                    NetBay.Core.Mail.SMTP.Assync.Smtp.SendMail(p_sSmtpServer, "[RIO - Alerte] " + l_oCurrentAlert.Object, l_oCurrentAlert.Body, l_oSenderMailAdress, l_oLstMailAddresses, null, null, p_sSmtpLogin, p_sSmtpPassword);
                    DataAccessLayer.DataAccessManager.UpdateAlert(l_oCurrentAlert.Identifier, 0, (int)Constants.Enums.AlertEnums.StatusEnum.Sent);
                }
                catch(ArgumentNullException ex)
                {
                    NetBay.Core.Log.LogManager.Instance().LogError("-------- Exception in SendAlerts Sender EmailAdress is not valid ArgumentNullException [" + l_oCurrentAlert.UserEmail + "] exception[" + ex.Message + "]" );
                    DataAccessLayer.DataAccessManager.UpdateAlert(l_oCurrentAlert.Identifier, 0, (int)Constants.Enums.AlertEnums.StatusEnum.Error);
                }
                catch(ArgumentException ex)
                {
                    NetBay.Core.Log.LogManager.Instance().LogError("-------- Exception in SendAlerts Sender EmailAdress is not valid ArgumentException [" + l_oCurrentAlert.UserEmail + "] exception[" + ex.Message + "]" );
                    DataAccessLayer.DataAccessManager.UpdateAlert(l_oCurrentAlert.Identifier, 0, (int)Constants.Enums.AlertEnums.StatusEnum.Error);
                }
                catch(FormatException ex)
                {
                    NetBay.Core.Log.LogManager.Instance().LogError("-------- Exception in SendAlerts Sender EmailAdress is not valid FormatException [" + l_oCurrentAlert.UserEmail + "] exception[" + ex.Message + "]" );
                    DataAccessLayer.DataAccessManager.UpdateAlert(l_oCurrentAlert.Identifier, 0, (int)Constants.Enums.AlertEnums.StatusEnum.Error);
                }
                catch ( Exception ex )
                {
                    NetBay.Core.Log.LogManager.Instance().LogError("-------- Exception in SendAlerts exception [" + ex.Message + "]");
                    DataAccessLayer.DataAccessManager.UpdateAlert(l_oCurrentAlert.Identifier, 0, (int)Constants.Enums.AlertEnums.StatusEnum.Error);
                }
            }
        }
    }
}
